package net.lovesrc.allin.biz.idcard;

import com.alibaba.fastjson.JSONObject;
import com.google.common.io.Files;
import com.zhouzhou.fastjava.util.FileKit;
import net.lovesrc.allin.Message;
import net.lovesrc.allin.controller.BaseController;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/id-card")
public class IdCardController extends BaseController {

    @Autowired
    private IdCardService idCardService;

    @PostMapping("/save")
    public Message save(
            String idCardNumber,
            String realName,
            MultipartFile file1,
            MultipartFile file2,
            MultipartFile file3
    ) throws IOException {
        idCardService.save(realName, idCardNumber, file1, file2, file3);
        return Message.success();
    }

    @GetMapping("/view/{idCardNumber}/{fileX}")
    public void save(
            @PathVariable String idCardNumber,
            @PathVariable String fileX,
            HttpServletResponse response) throws IOException {
        File dir = new File(IdCardService.ROOT, idCardNumber);
        File file;
        if (fileX.equals("file1")) {
            file = FileKit.tryGetFile(dir, "1", IdCardService.ACCEPT_EXTENSIONS);
        } else if (fileX.equals("file2")) {
            file = FileKit.tryGetFile(dir, "2", IdCardService.ACCEPT_EXTENSIONS);
        } else {
            file = FileKit.tryGetFile(dir, "3", IdCardService.ACCEPT_EXTENSIONS);
        }
        response.setContentType(FileKit.getConentType(file.getName()));
        IOUtils.copy(
                new FileInputStream(file),
                response.getOutputStream()
        );
        response.flushBuffer();
    }

    @GetMapping("/scan")
    public Message scan() throws Exception {
        File root = IdCardService.TMP_ROOT;
        doScan(root);
        return Message.success();
    }

    private void doScan(File parent) throws Exception {
        if (!parent.isDirectory()) {
            return;
        }
        File[] files = parent.listFiles();
        for (File file : files) {
            if (!file.isDirectory()) {
                continue;
            }
            File file1 = FileKit.tryGetFile(file, "1", IdCardService.ACCEPT_EXTENSIONS);
            File file2 = FileKit.tryGetFile(file, "2", IdCardService.ACCEPT_EXTENSIONS);
            File file3 = FileKit.tryGetFile(file, "3", IdCardService.ACCEPT_EXTENSIONS);
            File txtFile = FileKit.tryGetFile(file, "信息.txt");
            if (file1 == null
                    || file2 == null
                    || file3 == null
                    || txtFile == null) {
                doScan(file);
                continue;
            }
            InputStream fis = new FileInputStream(txtFile);
            String text = IOUtils.toString(fis,"gbk");
            fis.close();
            if (StringUtils.isBlank(text)) {
                continue;
            }
            text = StringUtils.trim(text);
            String[] strs = text.split("\\-+");
            if (strs.length != 2) {
                continue;
            }
            String realName = new String(StringUtils.trim(strs[0]).getBytes("utf-8"),"utf-8");
            String idCardNumber = StringUtils.trim(strs[1]);
            if (idCardNumber.length() != 18) {
                continue;
            }
            idCardNumber = idCardNumber.toUpperCase();
            File targetFolder = new File(IdCardService.ROOT, idCardNumber);
            if (targetFolder.exists()) {
                String parentPath = parent.getParent();
                String repeatIdcardPath=parentPath+File.separatorChar+"idcard-files-repeated";
                File repeatIdcardPathFile =new File(repeatIdcardPath);
                if (!repeatIdcardPathFile.exists()){
                    repeatIdcardPathFile.mkdir();
                }
                 Files.move(file, new File(repeatIdcardPath, System.currentTimeMillis() + "__" + idCardNumber));
                continue;
            }
            Integer count = jdbcTemplate.queryForObject("select count(1) from t_id_card where idCardNumber = ?", int.class, idCardNumber);
            if (count == 0) {
                // insert
                JSONObject newRow = new JSONObject()
                        .fluentPut("idCardNumber", idCardNumber)
                        .fluentPut("realName", realName)
                        .fluentPut("file1Bytes", file1.length())
                        .fluentPut("file2Bytes", file2.length())
                        .fluentPut("file3Bytes", file3.length());
                insertRow(jdbcTemplate, "t_id_card", newRow);
            } else {
                // update
                jdbcTemplate.update("update t_id_card set realName = ?, file1Bytes = ?, file2Bytes = ?, file3Bytes = ? where idCardNumber = ?",
                        realName, file1.length(), file2.length(), file3.length(), idCardNumber);
            }
            Files.move(file, targetFolder);
        }
    }

    public static void main(String[] args) {
        File parent =new File("E:/data/idcard-files");
        String parentPath = parent.getParent();
        String repeatIdcardPath=parentPath+File.separatorChar+"idcard-files-repeated";
        File repeatIdcardPathFile =new File(repeatIdcardPath);
        if (!repeatIdcardPathFile.exists()){
            repeatIdcardPathFile.mkdir();
        }
    }

}
